package org.datacoder.geocoding.jurisdiction

import org.datacoder.util.*

class CountryService {

    def jurisdictionService
    def stateService

    static transactional = true

    /* CRUD */
    public Country create(Country country) throws DAOException{
        save(country)
        return country
    }
    public void save(Country country) throws DAOException{
        ServiceUtils.save(country)
    }
    public void save(Country country, boolean flush) throws DAOException{
        ServiceUtils.save(country, flush)
    }
    public void delete(Country country){
        if(country == null){
            return
        }
        jurisdictionService.deleteHeldOfficesAndIssues(country)
        if(country.states != null){
            Set<State> states = new HashSet<State>(country.states)
            for(state in states){
                stateService.delete(state)
            }
        }
        country.delete(flush:true)
    }
    public Country merge(Country country){
        return country.merge()
    }
    public Country get(String countryId){
        return get(Long.parseLong(countryId))
    }
    public Country get(long countryId){
        return Country.get(countryId)
    }
    public Set<Country> getAll(){
        return Country.findAll()
    }
    /* END CRUD */

    public Country getByNameOrCreate(String name, String longName){
        Country country = getByName(name)
        if(country == null){
            country = new Country(
                name:name,
                longName:longName
            )
            country = create(country)
        }
        return country
    }

    public Country getByName(String name){
        Country country = Country.findByName(name)
        return country
    }
}

